package io.renren.wechat.service.suite;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author dmcp@qq.com
 * @since 2021/11/14 21:52
 */
@Component
public class SuiteTicketService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SuiteTicketService.class);
    private StringRedisTemplate stringRedisTemplate;
    private static final int SUITE_TICKET_TIMEOUT_IN_MINUTES = 30;
    private static final int AUTHCODE_TIMEOUT_IN_MINUTES = 30;


    public String getSuiteTicket(String suiteId) {
        String suiteTicketFromCache = getSuiteTicketFromCache(suiteId);

        if (StringUtils.isBlank(suiteTicketFromCache)) {
            LOGGER.warn("!!!!no suite ticket in redis............");
            throw new RuntimeException("suite ticket for suiteId=[" + suiteId + "]暂时未同步过来，请稍后再试！");
        }

        return suiteTicketFromCache;
    }

    public String getAuthCode(String suiteId) {
        String cacheKey = buildAuthCodeCacheKey(suiteId);

        String authCode = stringRedisTemplate.opsForValue().get(cacheKey);

        if (StringUtils.isBlank(authCode)) {
            LOGGER.warn("!!!!no auth code in redis............");
            throw new RuntimeException("auth code for suiteId=[" + suiteId + "]暂时未同步过来，请稍后再试！");
        }

        LOGGER.debug("got auth code with suiteId: {} from cache: {}", suiteId, authCode);
        return authCode;
    }

    public void cacheSuiteTicket(String suiteId, String suiteTicket) {
        final String cacheKey = buildSuiteTicketCacheKey(suiteId);

        stringRedisTemplate.opsForValue().set(cacheKey, suiteTicket, SUITE_TICKET_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
    }

    public void cacheAuthCode(String suiteId, String authCode) {
        final String cacheKey = buildAuthCodeCacheKey(suiteId);

        stringRedisTemplate.opsForValue().set(cacheKey, authCode, AUTHCODE_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
    }

    public String getSuiteTicketFromCache(String suiteId) {
        final String cacheKey = buildSuiteTicketCacheKey(suiteId);

        return stringRedisTemplate.opsForValue().get(cacheKey);
    }

    private String buildSuiteTicketCacheKey(String suiteId) {
        return String.format("suite_ticket:%s", suiteId);
    }

    private String buildAuthCodeCacheKey(String suiteId) {
        return String.format("authCode:%s", suiteId);
    }

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
}
